package main;

public class IOController {
	private IO ioInstance;
	private Field field;
	
	private int x, y;
	private int fieldHeight, fieldWidth;
	
	//constructor
	/*
	 * @param	ioInstance	the IO object to be referenced for input and output
	 * @see		IO
	 */
	public IOController(IO ioInstance){
		this.ioInstance = ioInstance;
		x = 0;
		y = 0;
		fieldHeight = 1;
		fieldWidth = 1;
	}

	//set field, call in the initialization stage
	/*
	 * @param	field	the Field object which provide the information of the field
	 * @see		field
	 */
	public void setField(Field field){
		this.field = field;
		fieldHeight = this.field.getHeight();
		fieldWidth = this.field.getWidth();
	}
	
	//show new round screen
	public void showNewRoundScreen(){
		showField('O', ' ', 'O');
		startNewRound();
	}
	
	//show end game screen
	public void showEndGameScreen(){
		showField('X', ' ', ' ');
		ioInstance.showMsg("Game over!\n");
	}
	
	//start new round
	private void startNewRound(){
		do{
			x = ioInstance.getInput("x-coordinate");
		}while(!isValidValue(x, 0, fieldWidth - 1));
		
		do{
			y = ioInstance.getInput("y-coordinate");
		}while(!isValidValue(y, 0, fieldHeight - 1));
		
		ioInstance.propagateInput(x, y);
	}
	
	//check value
	/*
	 * @param	value			value to be checked
	 * @param	lowestValue		the lowest value of the checked range
	 * @param	highestValue	the highest value of the checked range
	 */
	private boolean isValidValue(int value, int lowestValue, int highestValue){
		return (value >= lowestValue && value <= highestValue);
	}
	
	//show field
	/*
	 * @param	bomb		char that actually shown to the user of a bomb
	 * @param	clicked		char that actually shown to the user of a clicked cell
	 * @param	available	char that actually shown to the user of a available cell
	 */
	private void showField(char bomb, char clicked, char available){
		char[][] currentField = new char[fieldHeight][fieldWidth];
		
		//set show field char
		for(int i = 0; i < fieldHeight; i ++){
			for (int j = 0; j < fieldWidth; j ++){
				int cellValue = field.getCell(i, j);
				char cellVisual = ' ';
				switch(cellValue){
					//clicked
					case -2:
						cellVisual = clicked;
						break;
					//bomb
					case -1:
						cellVisual = bomb;
						break;
					//available
					case 0:
						cellVisual = available;
						break;
					//other
					default:
						cellVisual = Integer.toString(cellVisual).charAt(0);
				}
				
				currentField[i][j] = cellVisual;
			}
		}
		ioInstance.showField(currentField, fieldWidth, fieldHeight);
	}
	
	
}
